layui.use([ 'form', 'table' ], function() {
	var form = layui.form;
	var table = layui.table;
	var roleData;
	var $ = layui.$, active = {
		    reload: function(){
		      var usernameText = $('#usernameText');
		      var nameText = $('#nameText');
		      var departmentText = $("#departmentText");
		      var roleText = $("#roleText");
		      //执行重载
		      table.reload('userReload', {
		        page: {
		          curr: 1 //重新从第 1 页开始
		        }
		        ,where: {
		            username: usernameText.val(),
		            name: nameText.val(),
		            department: departmentText.val(),
		            role_id: roleText.val()
		        }
		      });
		    }
	};

	/* 异步角色Select */
	var url = "../../sysrole/roleSelection";
	$.post(url, function(result) {
		var role = JSON.parse(result);
		roleData = role.sysrole;
		var roleText = document.getElementById("roleText");
		var roleSelect = $("#roleSelect");
		$.each(roleData, function(index, data) {
			var deptOption = $("<option value='" + data.id + "'>" + data.name + "</option>");
			roleText.options.add(new Option(data.name,data.id));
			roleSelect.append(deptOption);
		});
		form.render('select');
	});
	
	/* 异步部门Select */
	var url = "../../sysrole/departmentSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var departments = data.department;
		var roleSelect = $("#departmentSelect");
		$.each(departments, function(index, data) {
			var deptOption = $("<option value='" + data.dept_id + "'>" + data.dept_name + "</option>");
			//departmentText.options.add(new Option(data.dept_name,data.dept_id));
			roleSelect.append(deptOption);
		});
		form.render('select');
	});
	
	/* 异步职位Select */
	var url = "../../sysrole/positionSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var position = data.position;
		var positionSelect = $("#positionSelect");
		$.each(position, function(index, data) {
			var positionOption = $("<option value='" + data.id + "'>" + data.positionname + "</option>");
			positionSelect.append(positionOption);
		});
		form.render('select');
	});
	
	table.render({
		elem : '#sysuserTable',
		url : '../../sysuser/userList',
		toolbar : '#toolbarSysuser',
		title : '用户数据表',
		cols : [ [ {
			type : 'checkbox',
			fixed : 'left'
		}, {
			field : 'id',
			title : 'ID',
			width : 100,
			fixed : 'left',
			unresize : true,
			sort : true
		}, {
			field : 'name',
			title : '姓名',
			sort : true
		}, {
			field : 'username',
			title : '用户名',
			sort : true
		}, {
			field : 'dept_name',
			title : '用户部门',
			sort : true
		},{
			field : 'positionName',
			title : '用户职位',
			sort : true
		},{
			field : 'role_id',
			title : '角色ID',
			sort : true
		}, {
			field : 'is_delete',
			title : '是否销户'
		}, {
			fixed : 'right',
			title : '操作',
			toolbar : '#barSysuser',
			width : 150
		} ] ],
		id : 'userReload',
		page : true,
		height: $(window).height() -50,
		done : function() {	
			$("[data-field='is_delete']").children().each(function() {
				if ($(this).text() == '1') {
					$(this).text("否")
				} else if ($(this).text() == '0') {
					$(this).text("是")
				}
			});
			$("[data-field='role_id']").children().each(function() {
				for(var i = 0; i < roleData.length; i++){
					if ($(this).text() == roleData[i].id) {
						$(this).text(roleData[i].name);
						break;
					}
				}
			})
		}
	});

	//头工具栏事件
	table.on('toolbar(sysuserTable)', function(obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
		case 'getCheckData':
			var data = checkStatus.data;
			layer.alert(JSON.stringify(data));
			break;
		case 'getCheckLength':
			var data = checkStatus.data;
			layer.msg('选中了：' + data.length + ' 个');
			break;
		case 'isAll':
			layer.msg(checkStatus.isAll ? '全选' : '未全选');
			break;
		};
	});

	//监听行工具事件
	table.on('tool(sysuserTable)', function(obj) {
		var data = obj.data;
		//console.log(obj)
		if (obj.event === 'del') {
			layer.confirm('真的删除用户么', function(index) {
				obj.del();
				userDelete(data.id);
				layer.close(index);
			});
		} else if (obj.event === 'edit') {
			/* 再弹出编辑界面 */
			layer.open({
				type : 1,
				title : "编辑用户",
				skin : "myclass",
				area : [ "40%" ],
				btn : [ '保存', '取消' ],
				content : $("#userAdd"),
				success : function(layero) {
					$('#sysname').val(data.name);
					$('#roleSelect').val(data.role_id);
					$('#departmentSelect').val(data.department);
					$('#positionSelect').val(data.positionId);
					$('#is_delete').val(data.is_delete);
					$('#username').val(data.username);
					$('#password').val(data.password);
					var btn = layero.find('.layui-layer-btn');
					btn.css('text-align', 'center');
					/* 渲染表单 */
					form.render();
				},
				yes : function(index, layero) {
					var sysname = $('#sysname').val();
					var roleSelect = $('#roleSelect option:selected').val();//获取当前选择项.
					var departmentSelect = $('#departmentSelect option:selected').val();//获取当前选择项.
					var is_delete = $('#is_delete option:selected').val();
					var positionId = $('#positionSelect option:selected').val();
					var username = $('#username').val();
					var password = $('#password').val();
					$.ajax({
						type : "POST",//方法类型
						dataType : "json",//预期服务器返回的数据类型
						url : "../../sysuser/userAdd",//url
						data : {
							sysname : sysname,
							roleSelect : roleSelect,
							departmentSelect : departmentSelect,
							is_delete : is_delete,
							username : username,
							password : password,
							id : data.id,
							positionId: positionId,
							},
						success : function(result) {
							if (result.code == 0) {
								layer.close(index);
								window.location.reload();
							};
						},
						error : function() {
							layer.msg('编辑用户失败');
							layer.close(index);
						}
					});
				}
			});
		}
	});

	$('.userTable .layui-btn').on('click', function() {
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});

	function userDelete(id) {
		$.ajax({
			url : '../../sysuser/userDelete?id=' + id,
			contentType : "application/json;charset=utf-8",
			type : 'post',
			success : function(data) {
				var json = JSON.parse(data);
				if (json.code == '0') {
					layer.msg('删除用户成功');
				} else {
					layer.msg('删除用户失败');
				}
			}
		})
	}

	/* 点击添加按钮提出添加员工界面 */
	$("#addEmplpyeeBtn").click(function() {
		/* 再弹出添加界面 */
		layer.open({
			type : 1,
			title : "添加用户",
			skin : "myclass",
			area : [ "40%" ],
			btn : [ '保存', '取消' ],
			content : $("#userAdd"),
			success : function(layero) {
				var btn = layero.find('.layui-layer-btn');
				btn.css('text-align', 'center');
				/* 渲染表单 */
				form.render();
				document.getElementById("addEmployeeForm").reset();//清空form表单的值 
			},
			yes : function(index, layero) {
				//限制输入框中不能用空值
			     var num=0;
			     $("#addEmployeeForm input[type$='text']").each(function(n){
			    	 if($(this).val()==""){
				    	num++
			    	 }		         
			     });
			     if(num>0){
			    	 layer.msg('输入框不能为空');
			    	 return false;
			     }
				var sysname = $('#sysname').val();
				var roleSelect = $('#roleSelect option:selected').val();//获取当前选择项.角色
				var departmentSelect = $('#departmentSelect option:selected').val();//获取当前选择项.部门
				var is_delete = $('#is_delete option:selected').val();
				var username = $('#username').val();
				var password = $('#password').val();
				$.ajax({
					type : "POST",//方法类型
					dataType : "json",//预期服务器返回的数据类型
					url : "../../sysuser/userAdd",//url
					data : {
						sysname : sysname,
						roleSelect : roleSelect,
						is_delete : is_delete,
						username : username,
						password : password,
						departmentSelect : departmentSelect
					},
					success : function(result) {
						if (result.code == 0) {
							layer.close(index);
							layer.msg('新增用户成功');
						}
						;
					},
					error : function() {
						layer.msg('新增用户失败');
						layer.close(index);
					}
				});
			}
		});
	});
	
	//监听用户名的输入框
	$('#usernameText').on("input propertychange", function() {
        active.reload();
    });
    
	//监听姓名的输入框
    $('#nameText').on("input propertychange", function() {
        active.reload();
    });
    
   //监听部门下拉框
   form.on("select(departmentFilter)",function(data){
  	 active.reload();
   });
   
 //监听角色用户框
   form.on("select(roleFilter)",function(data){
  	 active.reload();
   });
   
   form.render('select');
   
});